<template>
  <view class="job-list-page" @scroll="onScroll" style="height: 100vh; overflow-y: auto; padding-bottom: 140rpx;">
    <custom-tab-bar/>
    <!-- 使用封装的搜索组件 -->
    <JobHeader
      type="job"
      :currentTab="currentTab"
      @on-tab-change="handleTabChange"
      @handle-search="handleSearch"
      @go-to-province="goToProvinceList"
      @city-changed="handleCityChanged"
      @city-reset="handleCityReset"
      placeholder="搜索职位名称"
    ></JobHeader>

    <!-- 移除原职位列表代码，替换为组件 -->
    <JobList 
      :job-list="jobList" 
      :loading-more="loadingMore" 
      :no-more="noMore"
      @goToJobDetail="goToJobDetail"
    />
    <!-- 空状态（无数据时） -->
    <view v-if="!isLoading && !errorMsg && jobList.length === 0" class="empty-container">
      <uni-icons type="info" size="48" color="#b6ccd8"></uni-icons>
      <text class="empty-text">暂无相关职位</text>
    </view>
  </view>
</template>

<script>
import { getJobPostings, getJobPosting } from '@/api/job.js';
import JobList from '@/components/JobList.vue';
import JobHeader from '@/components/search.vue';

export default {
  components: {
    JobList,
    JobHeader
  },
  data() {
    return {
      pageSize: 10,
      pageNum: 1,
      jobList: [],
      total: 0, // 总记录数
      isLoading: false,
      loadingMore: false,
      noMore: false,
      errorMsg: '',
      searchValue: '',
      city: '选择城市', // 默认城市
      currentTab: 0, // 当前选中的标签索引
    };
  },
  
  methods: {
    async fetchJobs(isLoadMore = false) {
      if (this.loadingMore || (isLoadMore && this.noMore)) {
        console.log('阻止重复加载或已无更多数据');
        return;
      }

      this.loadingMore = isLoadMore;
      this.isLoading = !isLoadMore;
      this.errorMsg = '';

      try {
        let res;
        const hasCity = this.city !== '选择城市';
        const hasKeyword = this.searchValue.trim() !== '';
        // 当城市为默认值时，传递空字符串
        const cityParam = hasCity ? this.city : '';

        if (hasCity || hasKeyword) {
          // 确保参数顺序与API定义一致
          res = await getJobPosting(this.pageNum, this.pageSize, this.searchValue, cityParam);
        } else {
          res = await getJobPostings(this.pageNum, this.pageSize);
        }

        const data = res.data || {};
        const currentPageData = data.list || [];
        this.total = data.total || 0;

        if (isLoadMore) {
          this.jobList = [...this.jobList, ...currentPageData];
        } else {
          this.jobList = currentPageData;
        }

        this.noMore = this.jobList.length >= this.total;
      } catch (error) {
        console.error('加载职位失败：', error);
        this.errorMsg = '加载失败，请检查网络后重试';
        if (isLoadMore) this.pageNum -= 1;
      } finally {
        this.isLoading = false;
        this.loadingMore = false;
      }
    },

    // 修复handleSearch方法，接收搜索关键词参数
    handleSearch(keyword) {
      console.log('搜索关键词：', keyword);
      this.searchValue = keyword; // 保存搜索关键词
      this.pageNum = 1;
      this.noMore = false;
      this.fetchJobs();
    },

    goToJobDetail(id) {
      uni.navigateTo({ url: `/pages/job/jobDetail/jobDetail?id=${id}` });
    },

    goToProvinceList() {
      // 跳转到城市列表页，传递type参数
      uni.navigateTo({
        url: `/pages/job/provinceList/provinceList?type=job`
      });
    },

    reload() {
      console.log('重新加载数据');
      this.pageNum = 1;
      this.noMore = false;
      this.fetchJobs();
    },

    // 处理城市变化
    handleCityChanged(city) {
      this.city = city;
      this.reload();
    },
    // 处理城市重置
    handleCityReset() {
      this.city = '选择城市';
      this.reload();
    },
    // 重命名原 onTabChange 为 handleTabChange
    handleTabChange(index) {
      console.log('切换到标签：', index);
      this.currentTab = index;
      this.pageNum = 1;
      this.noMore = false;
      this.fetchJobs();
    },
    // 其他方法保持不变
    // onTabChange(index) {
    //   console.log('切换到标签：', index);
    //   this.currentTab = index;
    //   this.pageNum = 1;
    //   this.noMore = false;
    //   this.fetchJobs();
    // }
  },

  onLoad() {
    console.log('页面加载，开始首次加载数据');
    this.fetchJobs();
  },

  onShow() {
    // 每次进入页面时重新加载数据
    this.fetchJobs();
  },

  // 删除以下全局事件监听代码
  mounted() {
  // 监听全局事件
  // uni.$on('job-city-selected', (city) => {
  //   this.city = city;
  //   this.reload();
  // });

  // uni.$on('job-city-reset', () => {
  //   this.city = '选择城市';
  //   this.reload();
  // });
  },

  beforeDestroy() {
  // 移除全局事件监听
  // uni.$off('job-city-selected');
  // uni.$off('job-city-reset');
  }
};
</script>


<style scoped>
.job-list-page {
  background-color: #f8f8f8;
  min-height: 100vh;
}

/* 搜索区域样式 */
.search-container {
  padding: 10px 15px;
  background-color: white;
}

.search-bar {
  display: flex;
  align-items: center;
  height: 40px;
  padding: 0 15px;
  background-color: #f5f5f5;
  border-radius: 20px;
}

.search-input {
  flex: 1;
  height: 100%;
  font-size: 14px;
  margin-left: 8px;
  background: transparent;
}

/* 自定义导航栏样式 */
.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #ffffff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-bottom: 1px solid #eaeaea;
  margin-bottom: 20rpx; 
}

.tab-item {
  padding: 10px 20px; /* 增加左右内边距，使标签更宽 */
  font-size: 16px; /* 调整字体大小 */
  cursor: pointer;
  transition: color 0.3s;
  color: #888; /* 未选中状态的颜色 */
}

.tab-item.active {
  color: #000; /* 选中状态的颜色 */
}

.location-container {
  display: flex;
  align-items: center;
}

.location {
  font-size: 16px;
  color: #333;
  padding: 5px 0;
  cursor: pointer;
  background-color: #f5f5f5;
  border-radius: 4px;
  display: inline-block;
  padding: 5px 10px;
}

/* 加载状态样式 */
.loading {
  text-align: center;
  padding: 30px 0;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

/* 错误状态样式 */
.error-state {
  text-align: center;
  padding: 30px 0;
  color: #f53f3f;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.error-state button {
  background-color: #007aff;
  color: white;
  padding: 8px 20px;
  border-radius: 4px;
  font-size: 14px;
}

/* 职位列表样式 */
.job-items {
  padding: 0 10px;
  /* 确保列表高度足够触发滚动 */
  min-height: calc(100vh - 100px);
}

.job-item {
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.job-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.job-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  max-width: 70%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.salary {
  color: #409eff;
  font-size: 16px;
  font-weight: bold;
}

.company-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  color: #666;
  font-size: 14px;
  gap: 10px;
}

.company-info text:first-child {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
  gap: 8px;
}

.tag {
  padding: 2px 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
}

.contact {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #999;
  font-size: 12px;
}

.contact-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.hr-avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background-color: #eee;
}

/* 加载更多提示 */
.load-more {
  text-align: center;
  padding: 15px 0;
  color: #999;
  font-size: 14px;
}

/* 空状态样式 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80px 0;
  color: #999;
}

.empty-text {
  margin-top: 15px;
  font-size: 16px;
}
</style>